<template>
  <div id="app">
    <h1>购物车</h1>
    
    <div class="cart-container">
      <div v-for="item in cartItems" :key="item.id" class="cart-item">
        {{ item.name }} - ￥{{ item.price }} - 数量：{{ item.quantity }}
        <button @click="decreaseQuantity(item.id)" class="quantity-btn">-</button>
        <button @click="increaseQuantity(item.id)" class="quantity-btn">+</button>
        <button @click="removeItem(item.id)" class="remove-btn">删除</button>
      </div>
      
      <div class="cart-total">
        总价：￥{{ cartTotal }}
      </div>
    </div>
    
    <AddProduct />
  </div>
</template>

<script>
import AddProduct from './components/AddProduct'

export default {
  name: 'App',
  components: {
    AddProduct
  },
  methods: {
    increaseQuantity(productId) {
      this.$store.dispatch('updateQuantity', {
        productId,
        quantity: this.getCurrentQuantity(productId) + 1
      })
    },
    decreaseQuantity(productId) {
      const currentQty = this.getCurrentQuantity(productId)
      if (currentQty > 1) {
        this.$store.dispatch('updateQuantity', {
          productId,
          quantity: currentQty - 1
        })
      } else {
        this.removeItem(productId)
      }
    },
    removeItem(productId) {
      this.$store.dispatch('removeFromCart', productId)
    },
    getCurrentQuantity(productId) {
      const item = this.cartItems.find(item => item.id === productId)
      return item ? item.quantity : 0
    }
  },
  computed: {
    cartItems() {
      return this.$store.getters.cartItems
    },
    cartTotal() {
      return this.$store.getters.cartTotal
    }
  }
}
</script>

<style>
#app {
  font-family: Arial, sans-serif;
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.cart-container {
  margin: 20px 0;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 5px;
}

.cart-item {
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
}

.cart-item > *:not(:last-child) {
  margin-right: 10px;
}

.cart-total {
  font-weight: bold;
  margin-top: 15px;
  padding-top: 10px;
  border-top: 1px solid #ddd;
}

h1 {
  text-align: center;
  color: #333;
}

.quantity-btn {
  width: 25px;
  height: 25px;
  border: 1px solid #ddd;
  background: #f5f5f5;
  cursor: pointer;
  border-radius: 3px;
}

.quantity-btn:hover {
  background: #e0e0e0;
}

.remove-btn {
  margin-left: auto;
  padding: 3px 8px;
  background: #ff6b6b;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}

.remove-btn:hover {
  background: #ff5252;
}
</style>